package com.swpu.eduservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swpu.commonutils.JwtUtils;
import com.swpu.commonutils.R;
import com.swpu.eduservice.Client.UcenterClient;
import com.swpu.eduservice.entity.EduComment;
import com.swpu.eduservice.entity.UcenterMember;
import com.swpu.eduservice.service.EduCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CommonsLogWriter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author ygq
 * @since 2021-10-30
 */
@RestController
@RequestMapping("/eduservice/comment")
public class EduCommentController {
    @Autowired
    private UcenterClient ucenterClient;
    @Autowired
    private EduCommentService commentService;

    //添加评论
    @PostMapping("/addComment")
    public R addComment(@RequestBody EduComment comment, HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(memberId)) {
            return R.error().code(28004).message("请登录");
        }
        comment.setMemberId(memberId);
        UcenterMember member = ucenterClient.getMenm(memberId);
        comment.setAvatar(member.getAvatar());
        comment.setNickname(member.getNickname());
        commentService.save(comment);
        return R.ok();
    }
    //分页获取评论
    @GetMapping("/{page}/{limit}")
    public R getCommentPage(@PathVariable long page,
                            @PathVariable long limit,
                            String courseId){
        Page<EduComment> pageParam = new Page<>(page,limit);
        QueryWrapper<EduComment> qw  = new QueryWrapper<>();
        qw.eq("course_id",courseId);
        commentService.page(pageParam,qw);
        List<EduComment> commentList = pageParam.getRecords();
        Map<String, Object> map = new HashMap<>();
        map.put("items", commentList);
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        map.put("hasNext", pageParam.hasNext());
        map.put("hasPrevious", pageParam.hasPrevious());
        return R.ok().data(map);
    }

}

